package servlet.ProductServlet;

import dao.ProductDAO;
import entity.ProductBean;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import myUtil.productCheck;

import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/ProductEditServlet")
public class ProductEditServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String type = request.getParameter("type");
        ProductBean product;
        if (type.equals("add")) {
            product = new ProductBean();
            product.setId(0);
            request.setAttribute("product", product);
            request.getRequestDispatcher("product_edit.jsp").forward(request, response);
        } else if (type.equals("mod")) {
            ProductDAO dao = new ProductDAO();
            int id = Integer.parseInt(request.getParameter("id"));
            product = dao.editProduct(id);
            request.setAttribute("product", product);
            request.getRequestDispatcher("product_edit.jsp").forward(request, response);
        } else if (type.equals("del")) {
            int id = Integer.parseInt(request.getParameter("id"));
            ProductDAO dao = new ProductDAO();
            int res = dao.deleteProduct(id);
            PrintWriter out = response.getWriter();
            if (res > 0) {
                out.println("删除数据成功");
                request.getRequestDispatcher("ProductListServlet").forward(request, response);
            } else {
                out.println("删除数据失败");
                response.setHeader("refresh", "3;ProductListServlet");
            }
        } else {
            throw new IllegalArgumentException("Wrong");
        }
    }
}

